package com.kgc.est.controller;

import com.kgc.est.feignService.PayOrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@RestController
@RequestMapping("/api/pay")
public class PayOrderController {

    Logger log = LoggerFactory.getLogger(PayOrderController.class);

    @Autowired(required = false)
    private PayOrderService payOrderService;

    /**
     *      生成支付订单信息
     *      去阿里付款界面
     *          去了阿里支付之后，后面跟二手兔相关的事情
     *          需要等到用户在支付宝付款成功后，阿里给二手兔发送支付成功的请求
     * @param orderNo
     */
    @GetMapping("/aliPay")
    public String aliPay(String orderNo){

        log.info("页面返回的商品订单编号：{}",orderNo);

        String result = payOrderService.aliPay(orderNo);
        return result;
    }

    /**
     * 接收支付宝发送给二手兔的请求
     *      二手兔需要对支付宝的请求进行验证
     *      在验证过程中会经常出问题
     * @param request
     * @param response
     */
    @RequestMapping("/aliPay/return")
    public void returnUrl(HttpServletRequest request, HttpServletResponse response){

        //获取支付宝返回的参数
        Map<String, String[]> parameterMap = request.getParameterMap();

        //对获取的参数进行转换
        HashMap<String, String> resultMap = new HashMap<>();

        Set<Map.Entry<String, String[]>> entries = parameterMap.entrySet();

        for (Map.Entry<String, String[]> entry : entries) {
            resultMap.put(entry.getKey(),entry.getValue()[0]);
        }
        log.info("支付宝返回的参数信息：{}",resultMap);

        //调service层代码，修改数据库的一些状态

        String retrunPath = payOrderService.updatePayOrder(resultMap);

        try {
            response.sendRedirect(retrunPath);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
